// Lindsay Gilmour
// Adam Lusch
// Dan Niceswanger
//
// Computer Graphics Project 2:
// Teapot racing!

#include "Ghostpot.h"
#include "PhysicsWorld.h"

#include <fstream>

Ghostpot::Ghostpot(b2World* w, GLdouble x, GLdouble z, GLdouble h, string filename)
	:Teapot()
{
	openGhost(filename);
	
	world = w;
	
	b2BodyDef bodyDef;
	bodyDef.position.Set(x, z);
	bodyDef.angle = h * M_PI / 180.0;
	bodyDef.linearDamping = 0.5;
	bodyDef.angularDamping = 50.0;
	body = world->CreateBody(&bodyDef);

	/*b2PolygonDef squareDef;
	squareDef.isSensor = true;
	squareDef.vertices[0] = b2Vec2(0.28, 0.22);
	squareDef.vertices[1] = b2Vec2(-0.28, 0.22);
	squareDef.vertices[2] = b2Vec2(-0.28, -0.22);
	squareDef.vertices[3] = b2Vec2(0.28, -0.22);
	
	squareDef.vertexCount = 4;
	squareDef.density = 50.0f;
	squareDef.friction = 500.0f;
	squareDef.restitution = 0.0;
	squareDef.userData = this;
	body->CreateShape(&squareDef);

	body->SetMassFromShapes();*/
}

Ghostpot::~Ghostpot()
{
}

double Ghostpot::getTotal()
{
	return totalTime;
}

vector <double> Ghostpot::getLaps()
{
	return lapTimes;
}

void Ghostpot::update()
{
	if (ghostPlay.size() > 0)
	{
		// Set X from deque, then pop
		float32 x = ghostPlay.at(0);
		ghostPlay.pop_front();
		
		// Set Z from deque, then pop
		float32 z = ghostPlay.at(0);
		ghostPlay.pop_front();
		
		// Set Heading from deque, then pop
		float32 heading = ghostPlay.at(0);
		ghostPlay.pop_front();
		
		b2Vec2 pos(x, z);
		body->SetXForm(pos, heading);
	}
}

void Ghostpot::openGhost(string filename)
{
	GLdouble x, z, angle;
	double tTime, lTime;
	
	ifstream ghostFile(filename.c_str());
	if (ghostFile.is_open())
	{
		clearData();
		
		ghostFile >> tTime;
		totalTime = tTime;
		
		if (PhysicsWorld::RACE_MODE == 1)
		{
			for (int i = 0; i < PhysicsWorld::LAP_COUNT; i++)
			{
				ghostFile >> lTime;
				lapTimes.push_back(lTime);
			}
		}
		else if (PhysicsWorld::RACE_MODE == 0)
		{
			ghostFile >> lTime;
			lapTimes.push_back(lTime);
		} 

		while (!ghostFile.eof())
		{
			ghostFile >> x;
			ghostFile >> z;
			ghostFile >> angle;

			addData(x);
			addData(z);
			addData(angle);
		}
		ghostFile.close();
	}
	else
	{
		totalTime = 9999.9;
		lapTimes.push_back(9999.9);
	}
}

void Ghostpot::addData(GLdouble data)
{
	ghostPlay.push_back(data);
}

void Ghostpot::clearData()
{
	ghostPlay.clear();
}
